package com.hs.jhzd.service.task;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import org.springframework.util.CollectionUtils;
import com.hs.jhzd.entity.Prisoner;
import com.hs.jhzd.entity.PrisonerAccount;
import com.hs.jhzd.entity.Task;
import com.hs.jhzd.repository.PrisonerAccountRepository;
import com.hs.jhzd.repository.PrisonerRepository;
import com.hs.jhzd.repository.TaskRepository;
import lombok.Data;

@Data
public class PrisonerAccountSynchronizeTask implements Runnable {

  private PrisonerAccountRepository prisonerAccountRepository;

  private PrisonerRepository prisonerRepository;

  private TaskRepository taskRepository;

  private String id;

  @Override
  public void run() {
    Date lastSynchronizeTime = getLastSynchronizeTimeFromDb(id);
    List<Prisoner> prisoners =
        prisonerRepository.findByInPrisonDateAfterOrderByInPrisonDateDesc(lastSynchronizeTime);
    if (CollectionUtils.isEmpty(prisoners)) {
      return;
    }

    for (Prisoner prisoner : prisoners) {
      PrisonerAccount account = new PrisonerAccount();
      account.setMonthLimit(500.0);
      account.setName(prisoner.getName());
      account.setCardId(prisoner.getCardId());
      account.setRybh(prisoner.getRybh());
      prisonerAccountRepository.save(account);
    }

  }

  private Date getLastSynchronizeTimeFromDb(String id) {
    Date date = new Date();
    Optional<Task> tasko = taskRepository.findById(id);
    if (tasko.isPresent()) {
      Task task = tasko.get();
      Date lastSyncTime = task.getLastSyncTime();

      if (lastSyncTime == null) {
        task.setLastSyncTime(date);
        taskRepository.save(task);
        return date;
      } else {
        return lastSyncTime;
      }
    }
    return null;
  }
}
